/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CurrentEntrustFragmentPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.trade.TradeApi;
import io.bhex.sdk.trade.bean.OpenOrderRequest;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.app.event.OrderFilterEvent;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ToastUtils;

/**
 * ================================================
 * 描   述：委托单
 * ================================================
 */

public class CurrentEntrustFragmentPresenter extends BaseFragmentPresenter<CurrentEntrustFragmentPresenter.EntrustOrderUI> {

    private List<OrderBean> currentOrders = new ArrayList<>();
    //过滤集合
    private List<OrderBean> filterOrders = new ArrayList<>();
    private String orderPageId = "";
    private boolean isVisible=true;
    private OrderFilterEvent currentFilter = new OrderFilterEvent();

    public void loadMore() {
        getCurrentEntrustOrders(true);
    }

    public interface EntrustOrderUI extends AppUI {

        void showOrders(List<OrderBean> currentOrders);

        void loadMoreComplete();

        void loadMoreFailed();

        void loadEnd();

        List<OrderBean> getShowOrders();
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, CurrentEntrustFragmentPresenter.EntrustOrderUI ui) {
        super.onUIReady(activity, ui);
        getCurrentEntrustOrders(false);
//        TradeApi.SubOrderChange(new SimpleResponseListener<OpenOrderResponse>() {
//            @Override
//            public void onSuccess(OpenOrderResponse response) {
//                super.onSuccess(response);
//                if (CodeUtils.isSuccess(response, true)) {
//                    List<OrderBean> srcList = response.getArray();
//                    if(srcList != null && srcList.size() > 0) {
//                        for (int i = srcList.size() -1; i >= 0 ; i--) {
//                            OrderBean srcBean = srcList.get(i);
//                            boolean hasSrcBean = false;
//                            for (int j = 0; j < currentOrders.size(); j++) {
//                                if(srcBean.getOrderId().equalsIgnoreCase(currentOrders.get(j).getOrderId())){
//                                    currentOrders.remove(j);
//                                    if(srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
//                                        currentOrders.add(j, srcBean);
//                                    hasSrcBean = true;
//                                    break;
//                                }
//                            }
//                            if(hasSrcBean == false && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
//                                currentOrders.add(0,srcBean);
//
//                        }
//                        if (currentOrders != null) {
//                            getUI().showOrders(currentOrders);
//                            getUI().loadEnd();
//                        }
//                    }
//
//
//                }
//            }
//        });
    }

    @Override
    public void onResume() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OrderFilterEvent event){
        if (isVisible) {
            DebugLog.e("FILTER","当前委托开始过滤了");
            filterOrder(event);
        }
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
    }

    /**
     * 过滤订单
     * @param event
     */
    private void filterOrder(OrderFilterEvent event) {
        orderPageId="";
        currentFilter = event;
        if (!currentOrders.isEmpty()) {
            currentOrders.clear();
//            filterOrders.clear();
//            for (OrderBean orderBean : currentOrders) {
//                if (isMatchOrder(orderBean,event)) {
//                    filterOrders.add(orderBean);
//                }
//            }
//            getUI().showOrders(filterOrders);
        }

        getCurrentEntrustOrders(false);
    }

    private boolean isMatchOrder(OrderBean orderBean, OrderFilterEvent event) {
        if (!TextUtils.isEmpty(event.baseToken)) {
            if (!orderBean.getBaseTokenName().equalsIgnoreCase(event.baseToken)) {
                return false;
            }
        }
        if (!TextUtils.isEmpty(event.quoteToken)) {
            if (!orderBean.getQuoteTokenName().equalsIgnoreCase(event.quoteToken)) {
                return false;
            }
        }

        if (!TextUtils.isEmpty(event.orderStatus)) {
            if (!orderBean.getSide().equalsIgnoreCase(event.orderStatus)) {
                return false;
            }
        }
        if (!TextUtils.isEmpty(event.priceMode)) {
            return orderBean.getType().equalsIgnoreCase(event.priceMode);
        }

        return true;
    }

    /**
     * 获取当前委托
     *
     * @param isLoadMore
     */
    public void getCurrentEntrustOrders(final boolean isLoadMore) {
        if (!UserInfo.isLogin()) {
            if (isLoadMore) {
                getUI().loadMoreComplete();
            }
            return;
        }
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        if (isLoadMore) {
            if (currentOrders != null) {
                if (!currentOrders.isEmpty()) {
                    orderPageId = currentOrders.get(currentOrders.size() - 1).getOrderId();
                }
            }
        }else{
            orderPageId ="";
        }

        OpenOrderRequest requestData = new OpenOrderRequest();
        requestData.baseToken = currentFilter.baseToken;
        requestData.quoteToken = currentFilter.quoteToken;
        requestData.orderStatus = currentFilter.orderStatus;
        requestData.priceMode = currentFilter.priceMode;

        if (isLoadMore && !TextUtils.isEmpty(orderPageId)) {
            //加载更多
            requestData.orderPageId = orderPageId;

        }
        TradeApi.RequestFilterOpenOrder(requestData, new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
            }

            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<OrderBean> data = response.getArray();
                    if (data != null) {

                        if (isLoadMore) {
                            if (data != null) {
                                currentOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                currentOrders.clear();
                                currentOrders = data;
                            }
                        }
                        getUI().showOrders(currentOrders);

                        if (data.size()< AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        }else{
                            getUI().loadMoreComplete();
                        }
                    }else{
                        getUI().loadMoreComplete();
                    }

                }else{
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }


    /**
     * 撤销全部订单 (当前现实的订单)
     */
    public void revokeAllOrders() {
//        List<OrderBean> showOrders = getUI().getShowOrders();
//        if (showOrders == null) {
//            return;
//        }
//        if (showOrders != null) {
//            if (!showOrders.isEmpty()) {
//                for (OrderBean currentOrder : showOrders) {
//                    String orderId = currentOrder.getOrderId();
//                    cancelOrder(orderId,true);
//                }
//                ToastUtils.showShort(getActivity(), getString(R.string.string_submit_revoke_all_orders));
//                //刷新一遍委托单
//                getCurrentOrdinaryEntrustOrders(false);
//            }
//        }

        //全部撤单
        if (!UserInfo.isLogin()) {
            //去登录
            IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
            return;
        }
        TradeApi.RequestCancelAllOrder("", new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    DebugLog.w("Order", "撤单：" + response.isSuccess());
                    ToastUtils.showShort(getActivity(), getString(R.string.string_submit_revoke_all_orders));
                    getCurrentEntrustOrders(false);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_failed));
            }
        });
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @param isBatch
     */
    public void cancelOrder(String orderId, final boolean isBatch) {
        TradeApi.RequestCancelOrder(orderId, new SimpleResponseListener<OrderBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("",getString(R.string.string_loading_hint_text));
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OrderBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (!isBatch) {
                        ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_success));
                        getCurrentEntrustOrders(false);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (!isBatch) {
                    ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_failed));
                }
            }
        });
    }

}
